var uid;

getCookie();

$(function() {
	getTask();
})

function getCookie() {
	chrome.cookies.get({ url: 'http://tools.int800.com', name: '_gid' }, function(cookie) {
		if (cookie) {
			uid = cookie.value;
		} else {
			chrome.cookies.get({ url: 'http://tools.int800.com.cn', name: '_gid' }, function(cookie) {
				uid = cookie.value;
			});
		}
	});
}

async function getTask() {
	for (var i = 0; i < 10; i++) {
		if (uid) {
			break;
		} else {
			getCookie();
		}
		await delay(0.5);
	}
	var parames = {code: 'getTask', uid: uid};
	chrome.runtime.sendMessage(parames, function(response) {
		if (response.result) {
			$('#login_info').css('color', 'black');
			$('#login_info').text('平台已登录');
			var result_jsons = JSON.parse(response.result);
			if (200 == result_jsons.code) {
				result_jsons = result_jsons.result;
				for (var i in result_jsons) {
					var memedia_id = result_jsons[i].id;
					var site_id = result_jsons[i].siteid;
					var site_name = configs[site_id].site_name;
					var nickname = result_jsons[i].nickname;
					var auth_piece_dom = `<div class="auth-piece">` + 
											`<img class="pull-left site-img" src="./icons/${site_id}.png">` + 
											`<div class="pull-left auth-info">` + 
												`<span>${site_name}授权</span><br/>` + 
												`<span>${nickname}</span>` + 
											`</div>` + 
											`<div class="pull-right auth-btn">` + 
												`<a href="#" memedia_id="${memedia_id}" site_id="${site_id}" nickname=${nickname}><span class="glyphicon glyphicon-lock"></span>&nbsp;授权</a>` + 
											`</div>` + 
										`</div>`;
					$('#auth_list').append(auth_piece_dom);
				}
				$('.auth-btn a').each(function() {
					$(this).on('click', function() {
						auth($(this).attr('site_id'), $(this).attr('memedia_id'), $(this).attr('nickname'));
					});
				});
			}
		}
	});
}

function auth(site_id, memedia_id, nickname) {
	var login_url = configs[site_id].login_url;
	if (!['28856', '81'].includes(site_id)) {
		var cookie_url = configs[site_id].cookie_url;
		chrome.cookies.getAll({url: cookie_url}, function(cookies) {
			for(var i in cookies) {
				chrome.cookies.remove({url: cookie_url, name: cookies[i].name}, function(result) {
					console.log(result);
				});
			}
		});
		var Interval = setInterval(function() {
			chrome.cookies.getAll({url: cookie_url}, function(cookies) {
				if (0 == cookies.length) {
					clearInterval(Interval);
					chrome.runtime.sendMessage({code: 'login', memedia_id: memedia_id, nickname: nickname, uuid: null});
					create_Tab(login_url);
				}
			});
		}, 1000);
	} else {
		var uuid = guid();
		login_url += uuid;
		chrome.runtime.sendMessage({code: 'login', memedia_id: memedia_id, nickname: nickname, uuid: uuid});
		create_Tab(login_url);
	}
}

/*
* 创建标签
* @parame task_url 任务链接(task_url为空时不能创建标签)
*/
function create_Tab(task_url){
	if (!task_url) return; 
	chrome.tabs.create({
		url: task_url,
		active: true,
		pinned: false
	});
}

/*
* 延时
* @parame delay 秒
*/
function delay(delay) {
    return new Promise(resolve => {
        setTimeout(() => resolve("delay"), 1000 * delay);
    });
}

/*
* 输出
*/
function print(content, obj='') {
	if (isDebug) console.log(new Date().toLocaleString() + "    " + content, obj);
}

/*
* 发送请求
* @parame url
* @parame parames 请求参数(GET方式传'')
* @parame send_type 请求方式(GET/POST)
* @parame async 是否异步执行(true/false)
* @parame callback 回调函数(返回响应结果)
*/
function sendRequest(url, parames, send_type, async, callback){
	var request_temp = createXMLHttpRequest();
	request_temp.onreadystatechange = function(){
		if(request_temp && request_temp.readyState == 4 && request_temp.status == 200){
			callback(request_temp.responseText);
		}
	};
	request_temp.open(send_type, url, async);
	request_temp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 
	request_temp.send(parames);
	return request_temp;
}

/*
* http请求
*/
function createXMLHttpRequest() {  
    var xmlHttp;
    if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
        if (xmlHttp.overrideMimeType)
            xmlHttp.overrideMimeType('text/xml');
    } else if (window.ActiveXObject) {
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
            }  
        }  
    }  
    return xmlHttp;  
}

/**
* 判断字符串是否为空
* @parame obj 字符串
*/
function check_StrIsNull(obj) {
	return null == obj || obj.replace(/(^s*)|(s*$)/g, "").length == 0;
}

function guid() {
	return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
		var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
		return v.toString(16);
	});
}